package cn.com.oceansoft.osc.ms.utils;

import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wuzy
 * @created 2017-03-07-16:02
 * @email wzy@oceansoft.com.cn
 */
public class ExpressEmsUtil {



    private  String emsVision;
    private  String emsAppId;
    private  String emsAppSecret;
    private  String emsUrl;


    public String getEmsVision() {
        return emsVision;
    }

    public void setEmsVision(String emsVision) {
        this.emsVision = emsVision;
    }

    public String getEmsAppkey() {
        return emsAppId;
    }

    public void setEmsAppkey(String emsAppkey) {
        this.emsAppId = emsAppkey;
    }

    public String getEmsAppSecret() {
        return emsAppSecret;
    }

    public void setEmsAppSecret(String emsAppSecret) {
        this.emsAppSecret = emsAppSecret;
    }

    public String getEmsUrl() {
        return emsUrl;
    }

    public void setEmsUrl(String emsUrl) {
        this.emsUrl = emsUrl;
    }

    public String getSortParams(Map<String, String> params) {
        // 删掉sign参数
        params.remove("sign");
        String contnt = "";
        Set<String> keySet = params.keySet();
        List<String> keyList = new ArrayList<String>();
        for (String key : keySet) {
            String value = params.get(key);
            // 将值为空的参数排除
            if (!StringUtils.isBlank(value)) {
                keyList.add(key);
            }
        }
        Collections.sort(keyList, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                int length = Math.min(o1.length(), o2.length());
                for (int i = 0; i < length; i++) {
                    char c1 = o1.charAt(i);
                    char c2 = o2.charAt(i);
                    int r = c1 - c2;
                    if (r != 0) {
                        // char值小的排前边
                        return r;
                    }
                }
                // 2个字符串关系是str1.startsWith(str2)==true
                // 取str2排前边
                return o1.length() - o2.length();
            }
        });
        //将参数和参数值按照排序顺序拼装成字符串
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            contnt += key + params.get(key);
        }
        return contnt;
    }


    private  String byte2hex(byte [] buffer){
        String h = "";

        for(int i = 0; i < buffer.length; i++){
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if(temp.length() == 1){
                temp = "0" + temp;
            }
            h = h + " "+ temp;
        }

        return h;

    }

    public String sign(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            charset = "UTF-8";
        }
        String sign = "";
        try {
            content = new String(content.getBytes(charset), charset);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            sun.misc.BASE64Encoder base64Encode = new BASE64Encoder();
            sign = base64Encode.encode(md5.digest(content.getBytes(charset)));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }


    public Map<String,String> getParameter(Map<String,String> map) {
        Map<String,String> result = new HashMap<>();
        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strTime = fmt.format(new Date());
        result.put("timestamp",strTime);

        result.put("version",getEmsVision());
        result.put("format","json");

        result.put("app_key",getEmsAppkey());

        for (Map.Entry<String, String> entry : map.entrySet()) {

            result.put(entry.getKey(),entry.getValue());

        }
        String beforeSign = getSortParams(result)+getEmsAppSecret();
        String singStr = sign(beforeSign,"");
        result.put("sign",singStr);

        return  result;
    }


    public   String GetResponseFromService(Map<String,String> map) throws Exception {

        String  response= HttpClientUtil.doPostByMap(getEmsUrl(),map,"UTF-8");
        return   response;

    }

}


